package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //根据username从数据库查询
        Employee employee = employeeMapper.findByUsername(username);

        if (employee == null) {
            return ResultInfo.error("当前用户不存在");
        }

        //查看当前员工的状态
        if (employee.getStatus() != Employee.STATUS_ENABLE) {
            return ResultInfo.error("当前用户未激活");
        }

        //将前端传入的密码跟数据库加密的密码进行比对
        //将前端密码加密
        String passwordWithMd5 = SecureUtil.md5(password);

        //将加密密码跟数据库密码作对比
        String passwordFromDb = employee.getPassword();

        if (!StringUtils.equals(passwordWithMd5, passwordFromDb)) {
            return ResultInfo.error("密码错误");
        }

        //返回成功
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        List<Employee> employeeList = employeeMapper.findByName(name);
        return employeeList;
    }

    @Override
    public void save(Employee employee) {
        //补齐参数
        // id
        employee.setId(IdUtil.getSnowflake(1,1).nextId());

        //password
        String password = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(password);
        //status
        employee.setStatus(Employee.STATUS_ENABLE);

        //创建 修改时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//
//        //创建 修改人
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);

        //调用mapper保存
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        //调用mapper查询
        Employee employee = employeeMapper.findById(id);
        return employee;
    }

    @Override
    public void update(Employee employee) {
        //设置更新人，更新时间
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);

        //调用mapper
        employeeMapper.update(employee);
    }
}
